package com.da.javatest.thread.juc.future;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

/**
 * @author chenlida
 * @date 2020/7/12 23:58
 * 执行一批任务，然后消费执行结果
 */
public class Future4 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        List<Callable<Integer>> list = new ArrayList<>();
        int taskCount = 5;
        for (int i = taskCount; i > 0; i--) {
            int j = i;
            list.add(() -> {
                TimeUnit.SECONDS.sleep(j);
                return j;
            });
        }
        solve(executorService, list, a -> System.out.println(System.currentTimeMillis() + ":" + a));
        executorService.shutdown();
    }

    public static <T> void solve(Executor e, Collection<Callable<T>> solvers, Consumer<T> consumer)
        throws InterruptedException, ExecutionException {

        ExecutorCompletionService<T> ecs = new ExecutorCompletionService<>(e);
        for (Callable<T> solver : solvers) {
            ecs.submit(solver);
        }
        int n = solvers.size();
        for (int i = 0; i < n; i++) {
            T result = ecs.take().get();
            if (result != null) {
                consumer.accept(result);
            }
        }
    }
}
